<template>
  <TablePage>
    <template #top>
      <SearchForm
        ref="searchIns"
        :columns="categoryColumns"
        :keyword-search-data="[{ label: '设备类型', key: 'searchText' }]"
        :show-add-btn="false"
        @search="onSearchCategory"
      >
        <template #extraButtons>
          <PermissionBtn
            class="ml-4"
            :btn-props="{ type: 'primary' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showCreateModal"
            >新增设备类型
            <template #icon>
              <Icon type="icon-tianjia" />
            </template>
          </PermissionBtn>
          <PermissionBtn
            v-show="isEnterprise"
            class="ml-4"
            :btn-props="{ type: 'primary' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="useTemFn"
            >使用标准模板
          </PermissionBtn>
        </template>
      </SearchForm>
    </template>
    <SlTable
      class="equipment-type-table"
      :columns="columns"
      :row-key="isEnterprise ? 'equipmentTypeId' : 'defaultEquipmentTypeId'"
      :data-source="tableData"
      :pagination="(false as any)"
      :loading="tableLoading"
      :search-model="applySearchModel"
      :ignore-keys="['equipmentCategoryIds']"
    >
      <template #bodyCell="{ column, record }">
        <a-space v-if="column.key === 'oper'">
          <PermissionBtn :btn-props="{ type: 'link' }" :oper-type="OperPermissionType.MANAGE" @click="setFunc(record)"
            >设置点表功能</PermissionBtn
          >
          <PermissionBtn
            :btn-props="{ type: 'link' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showUpdateModal(record)"
            >编辑</PermissionBtn
          >
          <PermissionBtn
            :btn-props="{ type: 'link', danger: true }"
            :oper-type="OperPermissionType.MANAGE"
            @click="deleteRecord({ action: CURDAction.DELETE, record })"
            >{{ t("common.delete") }}</PermissionBtn
          >
        </a-space>
        <div
          v-if="column.dataIndex === 'defaultEquipmentTypeName' || column.dataIndex === 'equipmentTypeName'"
          class="flex flex-row items-center"
        >
          <div class="a-image-center">
            <a-image
              :src="record.defaultEquipmentTypePhoto || record.equipmentTypePhoto || emptyImg"
              :height="64"
              :width="64"
            ></a-image>
          </div>
          <div class="flex flex-col ml-4">
            <div class="flex flex-row items-center">
              <EllipsisText
                class="m-0 mb-2 font-semibold text-color-main text-lg"
                :max-len="20"
                :text="record.defaultEquipmentTypeName || record.equipmentTypeName || '--'"
              />

              <!-- <p class="m-0 mb-2 font-semibold text-color-main text-lg">{{
                record.defaultEquipmentTypeName || record.equipmentTypeName || "--"
              }}</p> -->
              <!-- <StateTag
                :color="record.defaultEquipmentTypeId ? '#4285F4' : '#38CE7B'"
                :value="record.defaultEquipmentTypeId ? '标准化' : '自定义'"
                class="h-6 ml-2 px-2"
              ></StateTag> -->
            </div>
            <p class="m-0">{{ record.defaultEquipmentTypeCode || record.equipmentTypeCode || "--" }}</p>
          </div>
        </div>
        <div v-if="column.key === 'isActive'">
          <a-switch
            v-model:checked="record.isActive"
            checked-children="开"
            un-checked-children="关"
            @change="handleChangeActiveFn(record)"
          />
        </div>
        <div v-else-if="column.dataIndex === 'equipmentTypePhoto'">
          <img v-if="record.equipmentTypePhoto" :src="record.equipmentTypePhoto" alt="logo" class="h-16" />
          <p v-else> - </p>
        </div>
        <div v-else-if="column.dataIndex === 'defaultEquipmentTypePhoto'">
          <img
            v-if="record.defaultEquipmentTypePhoto"
            :src="record.defaultEquipmentTypePhoto"
            alt="logo"
            class="h-16"
          />
          <p v-else> - </p>
        </div>
        <EllipsisText v-if="column.dataIndex === 'description'" :max-len="20" :text="record.description" />
        <EllipsisText v-if="column.dataIndex === 'descriptions'" :max-len="20" :text="record.descriptions" />
      </template>
    </SlTable>

    <CURDDialog
      :id-key="isEnterprise ? 'equipmentTypeId' : 'defaultEquipmentTypeId'"
      :columns="columns"
      :create-title="t('aiot.deviceType.add')"
      :update-title="t('aiot.deviceType.editDeviceType')"
      :check-title="t('aiot.deviceType.details')"
      :delete-message="t('aiot.deviceType.delDeviceType')"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :oper-data="operData"
      :curd="curd"
      :reload-table="reloadTable"
      :get-delete-params="delEquipmentTypeFn"
      :force-column="true"
      @before-ok="functionBeforeOk"
      @before-show="beforeShow"
    />
    <!-- 设备类别Curd -->
    <CURDDialog
      create-title="新增设备类别"
      update-title="编辑设备类别"
      delete-message="您确定删除该设备类别吗？"
      :show-options="cateGoryShowOptions"
      :columns="categoryColumns"
      :model-form-setting="cateGoryModelFormSetting"
      :model="cateGoryModel"
      :table-data="cateGoryTableData"
      :curd="categoryCurd"
      :id-key="isEnterprise ? 'equipmentCategoryId' : 'defaultEquipmentCategoryId'"
      :reload-table="cateGoryReloadTable"
      :get-delete-params="getUserDeleteParams"
      @before-ok="beforeOk"
      @ok="categoryOk"
    />
    <SetEquipmentFunction
      v-model:visible="equipmentFuncVisible"
      v-model:options="curEquipmentType"
      :is-enterprise="isEnterprise"
    />
    <a-modal v-if="isEnterprise" v-model:visible="templateVisible" title="使用标准模板" :width="1000" @ok="handleCopy">
      <EquipmentTypeSelect
        ref="equipmentTypeIns"
        v-model:value="selectedDefaultIds"
        :select-equipment-types="selectEquipmentTypes"
        :is-enterprise="false"
      />
    </a-modal>
  </TablePage>
</template>
<script lang="ts" setup>
import { onMounted, ref, shallowRef, watch, nextTick } from "vue";
import emptyImg from "/emptyImg.svg";
import { useI18n } from "/@/locales/useI18n";
import { DeviceTypeItem, ParDeviceTypeItem } from "/@/api/aiot/deviceType/models";
import SearchForm from "/@/components/SearchForm.vue";
import { useCURD } from "/@/hooks/useCURD";
import { CURDAction, CURDModalEvent, OperItem, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import { RequestMethodEnum } from "/@/api/req/httpEnum";
import SlTable from "/@/components/SlTable.vue";
import { OperPermissionType } from "/@/api/aiot/role/models";
import PermissionBtn from "/@/components/PermissionBtn.vue";
import { loopItem } from "/@/utils/treeData";
import { useDeviceType } from "./useDeviceType";
import { EquipmentCategorySearchModel, ParEquipmentCategoryItem } from "/@/api/aiot/equipmentCategory/models";
import { EquipmentTypeItem, ParEquipmentTypeItem } from "/@/api/aiot/equipment/models";
import { message } from "ant-design-vue";
import {
  updateEquipmentTypes,
  updateEquipmentTypesEnterprise,
  copyEquipmentTypes,
  equipmentPage,
} from "/@/api/aiot/deviceType";
import { pageEquipmentCategorySystem } from "/@/api/aiot/equipmentCategory";
import { DataNode } from "ant-design-vue/lib/tree";

let curAppId = "";
// 判断是否新增根目录
let isCreatingRootMenu = false;
const equipmentFuncVisible = ref<boolean>(false);
const equipmentTypeIns = ref();
const searchIns = ref();
// 当前选中的设备数据
const curSelectedDevice = ref<DeviceTypeItem | null>(null);
const { t } = useI18n();
const searchModel = [{ key: "searchText", label: "设备名称/编码" }];
const props = defineProps<{
  isEnterprise: boolean;
}>();
const { Api, model, modelFormSetting, columns, categoryColumns, cateGoryModelFormSetting, cateGoryModel } =
  useDeviceType(props.isEnterprise);

const showOptions = ref<ShowCURDModalOptions>();
const templateVisible = ref<boolean>(false);
const addEquipmentCategoryBtn = ref<boolean>(false);
const checkedKey = ref<string[]>([""]);
// 设备类别
const cateGoryShowOptions = ref<ShowCURDModalOptions>();
function setCategoryShowOptions(options: ShowCURDModalOptions) {
  cateGoryShowOptions.value = options;
}
function delDictType() {
  setCategoryShowOptions({ action: CURDAction.DELETE, record: curSelectCategory.value });
}
let selectedCategoryKeys = ref<string[]>([]);
const {
  curd: categoryCurd,
  tableData: cateGoryTableData,
  tableLoading: categoryTableLoading,
  reloadTable: cateGoryReloadTable,
  pagination: categoryPagination,
  searchModel: categorySearchModel,
} = useCURD<ParEquipmentCategoryItem, EquipmentCategorySearchModel>({
  getPageUrl: Api.pageEquipmentCategory,
  createUrl: Api.saveOrUpdateEquipmentCategory,
  updateUrl: Api.saveOrUpdateEquipmentCategory,
  deleteUrl: Api.deleteEquipmentCategoryByIds,
  loadOnMounted: false,
  onLoadSuccess(data) {
    loopItem(data, (el, i, items) => {
      if (!el.children || el.children.length === 0) {
        delete el.children;
      }
    });
    props.isEnterprise
      ? cateGoryTableData.value.unshift({
          equipmentCategoryName: "全部",
          equipmentCategoryId: "",
          parentCategoryId: "0",
        })
      : cateGoryTableData.value.unshift({
          equipmentCategoryName: "全部",
          defaultEquipmentCategoryId: "",
          parentCategoryId: "0",
        });
  },
});

// 自定义删除用户方法
const getUserDeleteParams = (id) => {
  return id ? [id] : selectedCategoryKeys.value;
};
const currentSelectRow = ref<ParEquipmentCategoryItem>({});
function beforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as ParEquipmentCategoryItem;
    if (e.action === CURDAction.CREATE && curEquipmentCategoryId.value) {
      model.parentCategoryId = curEquipmentCategoryId.value;
    }
  }
}
// 查询字典类型
async function onSearchCategory({ searchText }) {
  reloadTable({ size: 9999, current: 1, model: { searchText: searchText } });
  // handleIndexChange(0);
}

// 设备类别endding

function showCreateModal() {
  isCreatingRootMenu = true;
  // modelFormSetting[4].hide = true;
  showOptions.value = { action: CURDAction.CREATE };
}
function beforeShow(e) {
  if (e.action === CURDAction.UPDATE || e.action === CURDAction.CHECK) {
  }
}

const {
  tableData,
  tableLoading,
  curd,
  pagination,
  reloadTable,
  searchModel: applySearchModel,
} = useCURD<DeviceTypeItem>({
  createUrl: Api.addEquipmentTypes,
  deleteUrl: Api.deleteEquipmentTypeByIds,
  getPageUrl: Api.equipmentPage,
  updateUrl: Api.updateEquipmentTypes,
  getDataMethod: RequestMethodEnum.POST,
  loadOnMounted: false,
  onLoadSuccess(data) {
    loopItem(data, (el, i, items) => {
      if (!el.children || el.children.length === 0) {
        delete el.children;
      }
    });
  },
});
const curSelectCategory = shallowRef<ParEquipmentCategoryItem>();

const operData: OperItem<DeviceTypeItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
  },
  {
    label: t("common.delete"),
    type: "primary",
    danger: true,
    handler: deleteRecord,
  },
];
let selectEquipmentTypeKeys = ref<string[]>([]);
const rowSelection = {
  onChange: (selectedRowKeys: string[], selectedRows: ParEquipmentTypeItem[]) => {
    selectEquipmentTypeKeys.value = selectedRowKeys;
  },
  getCheckboxProps: (record: ParEquipmentTypeItem) => ({
    // disabled: record.name === "Disabled User", // Column configuration not to be checked
    // name: record.name,
  }),
};
// 自定义删除用户方法
const delEquipmentTypeFn = (id) => {
  return id ? [id] : selectEquipmentTypeKeys.value;
};
function showUpdateModal(record) {
  // modelFormSetting[4].hide = false;
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function showAddChildModal(record) {
  isCreatingRootMenu = false;
  curSelectedDevice.value = record;
  showOptions.value = { action: CURDAction.CREATE, record };
}
function deleteRecord(options) {
  showOptions.value = options;
}
function functionBeforeOk(e: CURDModalEvent) {
  if (e.model) {
    // const model = props.isEnterprise ? (e.model as DeviceTypeAiotItem) : (e.model as DeviceTypeItem);
    const model = e.model;
    if (e.action === CURDAction.CREATE) {
      model.equipmentCategoryId = curEquipmentCategoryId.value;
      // if (isCreatingRootMenu) {
      //   props.isEnterprise ? (model.parentEquipmentTypeId = "") : (model.equipmentTypeParentInnerId = "");
      // } else {
      //   props.isEnterprise
      //     ? (model.parentEquipmentTypeId = curSelectedDevice.value?.equipmentTypeId)
      //     : (model.equipmentTypeParentInnerId = curSelectedDevice.value?.rootId);
      // }
    }
  }
}
function setShowOptions(options: ShowCURDModalOptions) {
  showOptions.value = options;
}
const curEquipmentCategoryId = ref<string>("");
const equipmentTypeIds = ref<string[]>([]);
function handleSelectTreeNode(equipmentCategoryId, node) {
  let level = node?.node.pos ? node.node.pos.split("-") : [];
  if (level.length > 3) {
    addEquipmentCategoryBtn.value = true;
  } else {
    addEquipmentCategoryBtn.value = false;
  }
  curEquipmentCategoryId.value = equipmentCategoryId[0];
  searchIns?.value?.clearKeyword();
  let data: EquipmentTypeItem[] = [node.node];
  equipmentTypeIds.value = [];
  loopItem(data, (el, i, item) => {
    if (el.equipmentCategoryId) {
      equipmentTypeIds.value.push(el.equipmentCategoryId);
    } else if (el.defaultEquipmentCategoryId) {
      equipmentTypeIds.value.push(el.defaultEquipmentCategoryId);
    }
  });
  reloadTable({ size: 9999, model: { equipmentCategoryIds: equipmentTypeIds, searchText: "" } });
}
async function handleChangeActiveFn(row: ParDeviceTypeItem) {
  let req: boolean | null = false;
  if (props.isEnterprise) {
    let obj = {
      isActive: row.isActive,
      equipmentTypeId: row.equipmentTypeId,
    };
    req = await updateEquipmentTypesEnterprise(obj);
  } else {
    let obj = {
      isActive: row.isActive,
      defaultEquipmentTypeId: row.defaultEquipmentTypeId,
    };
    req = await updateEquipmentTypes(obj);
  }
  if (req) {
    message.success("操作成功");
    reloadTable();
  }
}
const selectedKeys = ref<string[]>([]);
onMounted(async () => {
  // await cateGoryReloadTable({
  //   size: 9999,
  //   model: {
  //     searchText: "",
  //     parentCategoryId: 0,
  //   },
  // });
  await reloadTable({ size: 9999, model: {} });
  // if (cateGoryTableData.value && cateGoryTableData.value.length > 0) {
  //   equipmentTypeIds.value = [];
  //   loopItem([cateGoryTableData.value[0]], (el, i, item) => {
  //     if (el.equipmentCategoryId) {
  //       equipmentTypeIds.value.push(el.equipmentCategoryId);
  //     } else if (el.defaultEquipmentCategoryId) {
  //       equipmentTypeIds.value.push(el.defaultEquipmentCategoryId);
  //     }
  //   });
  //   await reloadTable({ size: 9999, model: { equipmentCategoryIds: equipmentTypeIds.value } });
  //   selectedKeys.value = [
  //     cateGoryTableData.value[0].equipmentCategoryId || cateGoryTableData.value[0].defaultEquipmentCategoryId || "",
  //   ];
  //   curEquipmentCategoryId.value =
  //     cateGoryTableData.value[0].equipmentCategoryId || cateGoryTableData.value[0].defaultEquipmentCategoryId || "";
  // }
});
const curEquipmentType = ref<{ equipmentTypeId: string; equipmentTypeName: string; defaultEquipmentTypeId: string }>({
  equipmentTypeId: "",
  equipmentTypeName: "",
  defaultEquipmentTypeId: "",
});

function setFunc(record) {
  equipmentFuncVisible.value = true;
  curEquipmentType.value = {
    equipmentTypeId: props.isEnterprise ? record.equipmentTypeId : record.defaultEquipmentTypeId,
    equipmentTypeName: props.isEnterprise ? record.equipmentTypeName : record.defaultEquipmentTypeName,
    defaultEquipmentTypeId: record.defaultEquipmentTypeId,
  };
}
function addEquipmentCategory() {
  setCategoryShowOptions({ action: CURDAction.CREATE });
}
function categoryOk() {
  curEquipmentCategoryId.value = "";
  cateGoryReloadTable();
}
const selectEquipmentTypes = ref<EquipmentTypeItem[]>([]);
const selectedDefaultIds = ref<string[]>([]);
async function useTemFn() {
  templateVisible.value = true;
  let equipmentTypeList = (await equipmentPage())?.records || [];
  selectEquipmentTypes.value = [];

  nextTick(() => {
    equipmentTypeList &&
      equipmentTypeList.length > 0 &&
      equipmentTypeList.forEach((item) => {
        if (item.defaultEquipmentTypeId) {
          selectEquipmentTypes.value.push(item);
          selectedDefaultIds.value.push(item.defaultEquipmentTypeId);
        }
      });
  });
}
async function handleCopy() {
  if (!curEquipmentCategoryId.value) {
    message.warning("请选择设备类别再做此操作");
    return;
  }
  let selectedRow = equipmentTypeIns.value.getSelecedEquipmentType() || [];
  if (selectedRow && selectedRow.length > 0) {
    selectedRow.forEach((item) => {
      item.equipmentCategoryId = curEquipmentCategoryId.value;
    });
    let req = await copyEquipmentTypes(selectedRow);
    if (req) {
      message.success("操作成功");
      templateVisible.value = false;
      reloadTable();
    }
  } else {
    message.warning("请选择类型再做此操作");
  }
}
watch(templateVisible, (v) => {
  if (!v) {
    equipmentTypeIns.value?.reset();
  }
});
</script>
<style lang="less" scoped>
:deep(.ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected) {
  background-color: rgba(66, 133, 244, 0.1);
}
:deep(.ant-tree.ant-tree-block-node .ant-tree-list-holder-inner .ant-tree-node-content-wrapper) {
  height: 44px;
  display: flex;
  align-items: center;
}
:deep(.ant-tree .ant-tree-node-content-wrapper .ant-tree-iconEle) {
  padding-top: 2px;
}
:deep(.ant-tree-switcher) {
  display: flex;
  flex-direction: row;
  align-items: center;
}
:deep(.equipment-type-table .sl-table-container) {
  height: calc(100% - 81.75px);
}
</style>
